"""
Case Type   : 资源池化集群支持多链路
Case Name   : 主节点业务过程中，链路1注入网络闪断故障
Create At   : 2025/04/13
Owner       : @kyleze
Description :
    1.主机执行tpcc业务
    2.主节点链路1注入网络闪断故障
    3.查看tpcc业务执行结果
    4.查看集群状态
Expect      :
    1.成功
    2.成功
    3.tpcc执行成功
    4.集群正常
History     :
"""
import os
import unittest
import time

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.ComThread import ComThread

from yat.test import Node
from yat.test import macro


class MultipathTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.pri_user_node = Node('PrimaryDbUser')
        self.pri_root = Node(node="PrimaryRoot")
        self.ip_1 = macro.PRIMARY_LUN_IP.split()[0].strip()
        self.log.info("----获取备节点网络设备名称----")
        self.network_card = ''
        interfaces = self.pri_root.sh("ip -o addr show").result()
        for item in interfaces.split('\n'):
            if self.ip_1 in item:
                self.network_card = item.split(' ')[1].split(':')[0]
        self.log.info(self.network_card)

    def test_multipath(self):
        step = '--step1:主机执行tpcc业务 expect:成功--'
        self.log.info(step)
        tpcc_thread = ComThread(
            self.com.start_tpcc, args=(self.pri_root, macro.TPCC_PATH))
        tpcc_thread.setDaemon(True)
        tpcc_thread.start()
        time.sleep(20)

        step = '--step2:主节点链路1注入网络闪断故障 expect:成功--'
        self.log.info(step)
        for i in range(3):
            down_res = self.pri_root.sh(f'ifdown {self.network_card}').result()
            self.log.info(down_res)
            self.assertIn("successfully deactivated", down_res,
                          "执行失败" + step)
            time.sleep(10)
            up_res = self.pri_root.sh(f'ifup {self.network_card}').result()
            self.log.info(up_res)
            self.assertIn("successfully activated", up_res, "执行失败" + step)
            time.sleep(5)

        step = '--step3:查看tpcc业务执行结果 expect:tpcc执行成功--'
        self.log.info(step)
        tpcc_thread.join(1800)
        result = tpcc_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.TPCC_SUCCESS_MSG, result, '执行失败' + step)

        step = '--step4:查看集群状态 expect:集群正常--'
        self.log.info(step)
        cluster_status = self.primary_sh.get_db_cluster_status('status')
        self.log.info(cluster_status)
        self.assertTrue(cluster_status, "执行失败" + step)

    def tearDown(self):
        self.log.info(f'----{os.path.basename(__file__)} end----')

